package tech.anzhen.simple.rpc.support.rest;


import tech.anzhen.simple.rpc.support.RemoteServiceProxyFactorySupport;

import java.lang.reflect.Proxy;

public class RestProxyFactoryBean<T> extends RemoteServiceProxyFactorySupport<T> {

    private RestClient restClient;

    private Integer connectTimeout;

    private Integer readTimeout;

    private String baseAddress;

    private String defaultIdentity;

    public void setBaseAddress(String baseAddress) {
        this.baseAddress = baseAddress;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public void setReadTimeout(Integer readTimeout) {
        this.readTimeout = readTimeout;
    }

    public void setDefaultIdentity(String defaultIdentity) {
        this.defaultIdentity = defaultIdentity;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected synchronized T getRemoteProxy() {

        if (restClient == null) {
            restClient = new RestClient();
            if (connectTimeout != null) {
                restClient.setConnectTimeout(connectTimeout);
            }
            if (readTimeout != null) {
                restClient.setReadTimeout(readTimeout);
            }
            restClient.setDefaultIdentity(defaultIdentity);
        }

        String url = baseAddress;

        url = RestUtils.pathAppend(url, serviceInterface.getSimpleName());

        if (!url.endsWith("/")) {
            url = url + "/";
        }

        RestClientInvocationHandler h = new RestClientInvocationHandler(restClient, url);
        Object proxy = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceInterface}, h);
        return (T) proxy;
    }

}
